package controllers;

import helpers.CrawlerDomainHelper;
import helpers.IpHelper;
import helpers.UrlHelper;

import javax.servlet.ServletException;
import java.io.IOException;
import java.util.TreeMap;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import services.GetInfoDomain;
import systems.CurrentProcess;
import systems.RecentlyUpdate;

import models.DirectoryModel;
import models.DomainModel;
import models.GoogleAdsenceModel;
import models.GoogleAnalyticModel;
import models.IpAddressModel;
import entities.Domain;
import entities.IpAddress;

public class CheckWhoisServlet extends HttpServlet {
	public void doGet(HttpServletRequest request, HttpServletResponse response)
		throws IOException, ServletException {
		String name = (String) request.getParameter("q");
		
		Domain domain = null;
		
		if (name != null && UrlHelper.checkDomain(name)) {
			name = UrlHelper.getMainDomain(name);
			DomainModel domainModel = DomainModel.getInstance();
			domain = domainModel.get(name);
			if (domain == null) {
				//Get data
				domain = new Domain();
				domain.setDomain(name);
				domain.setExists(false);
				CrawlerDomainHelper crawler = new CrawlerDomainHelper();
				domain = crawler.getWhois(domain);
				
				if (domain != null && !domain.getWhois().isEmpty()) {
					domainModel.insert(domain);
				}
				
			}
		} 
		
		//Cache header
		response.addHeader("Cache-Control", "public, max-age=60000");
		
		request.setAttribute("name", name);
		request.setAttribute("domain", domain);
		try {
			request.getRequestDispatcher("/pages/check_whois.jsp").forward(request, response);
		} catch (ServletException e) {
			e.printStackTrace();
		}
	}
}
